<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" v-hasPermi="['system:project:query']" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button
          plain
          type="primary"
          @click="createForm('create')"
          v-hasPermi="['system:project:create']"
        >
          <Icon class="mr-5px" icon="ep:plus" />
          创建项目
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :show-overflow-tooltip="true">
      <el-table-column align="center" label="项目名称" prop="name" />
      <el-table-column align="center" label="项目ID" prop="code" />
      <!-- <el-table-column align="center" label="项目类型" prop="type">
        <template #default="scope">
          {{ scope.row.type == 1 ? '普通项目' : 'gitlab项目' }}
        </template>
</el-table-column> -->
      <el-table-column align="center" label="管理员" prop="managerName" />
      <el-table-column align="center" label="成员数" prop="members" />
      <el-table-column align="center" label="创建时间" prop="createTimeStr" />
      <el-table-column :width="300" align="center" label="管理">
        <template #default="scope">
          <template v-if="scope.row.type == 1">
            <div class="flex items-center justify-center">
              <el-button
                link
                type="primary"
                @click="updateForm('update', scope.row)"
                v-if="scope.row.allowModif != 0"
                v-hasPermi="['system:project:update']"
              >
                编辑
              </el-button>
              <el-button
                link
                type="primary"
                @click="
                  push(
                    `/projectMember/memberManage?projectId=${scope.row.id}&projectName=${scope.row.name}&defaulted=${scope.row.defaulted}`
                  )
                "
                v-hasPermi="['system:project:group:member:query']"
              >
                成员
              </el-button>
              <el-button link type="primary" @click="toPublish(scope.row.id)"> 接口 </el-button>
              <!-- <el-button link type="primary"
                @click="push(`/projectModule/moduleManage?projectId=${scope.row.id}&projectName=${scope.row.name}&defaulted=${scope.row.defaulted}`)">
                模板
              </el-button> -->
              <!-- 退出操作是否出现在更多里面 需要判断是否有编辑操作 -->
              <el-button
                link
                type="primary"
                @click="handleQuit(scope.row.id)"
                v-if="scope.row.allowModif == 0"
              >
                退出
              </el-button>
              <!-- 当前用户的默认项目不显示退出和删除 -->
              <!-- 如果退出或者删除操作存在 才显示更多 -->
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <el-button type="primary" link>
                  <el-icon style="transform: rotate(90deg)">
                    <MoreFilled />
                  </el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      @click="
                        push(
                          `/projectModule/moduleManage?projectId=${scope.row.id}&projectName=${scope.row.name}&defaulted=${scope.row.defaulted}`
                        )
                      "
                    >
                      模板
                    </el-dropdown-item>
                    <el-dropdown-item command="handleQuit" v-if="scope.row.allowModif != 0">
                      退出
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="handleDelete"
                      v-if="checkPermi(['system:project:delete']) && scope.row.allowDelete != 0"
                    >
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
          <template v-else>
            <el-button
              link
              type="primary"
              @click="push(`/projectUser/userManage?projectId=${scope.row.id}`)"
              v-hasPermi="['system:project:group:query']"
            >
              用户
            </el-button>
            <el-button
              link
              type="primary"
              @click="handleStore(scope.row.id)"
              v-hasPermi="['system:project:store:query']"
            >
              仓库
            </el-button>
            <el-button link type="primary" @click="handleUpdateKey"> 更新令牌 </el-button>
            <el-dropdown @command="(command) => handleCommand(command, scope.row)">
              <el-button type="primary" link>
                <el-icon style="transform: rotate(90deg)">
                  <MoreFilled />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    command="handleDelete"
                    v-if="checkPermi(['system:project:delete'])"
                    :disabled="scope.row.allowDelete == 0"
                  >
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />

    <!-- 表单弹窗：添加/修改 -->
    <ProjectForm ref="formRef" @success="getList" />
    <CreateProject ref="createFormRef" @success="getList" />
    <!-- 更新令牌 -->
    <UpdateKey ref="updateKeyRef" @success="getList" />
  </ContentWrap>
</template>
<script lang="ts" setup>
defineOptions({ name: 'Project' })
import * as ProjectApi from '@/api/project'
import ProjectForm from './ProjectForm.vue'
import CreateProject from './CreateProject.vue'
import UpdateKey from './UpdateKey.vue'
import { checkPermi } from '@/utils/permission'
import { useUserStore } from '@/store/modules/user'
import { MoreFilled } from '@element-plus/icons-vue'
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const userStore = useUserStore()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由对象
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([] as any) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: ''
})
const queryFormRef = ref() // 搜索的表单
const userName = computed(() => userStore.user.nickname ?? '')
import { useTagsViewStore } from '@/store/modules/tagsView'
const tagsViewStore = useTagsViewStore()

/** 操作分发 */
const handleCommand = (command: string, row) => {
  switch (command) {
    case 'handleDelete':
      handleDelete(row.id)
      break
    case 'handleQuit':
      handleQuit(row.id)
      break
    case 'handleUpdateKey':
      handleUpdateKey(row.id)
      break
    default:
      break
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProjectApi.getProjectList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加操作 */
const createFormRef = ref()
const createForm = (type: string) => {
  createFormRef.value.open(type)
}

/** 修改操作 */
const formRef = ref()
const updateForm = (type: string, row?: object) => {
  formRef.value.open(type, row)
}

// 删除
const handleDelete = async (id) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProjectApi.deleteProject({ id })
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}
const updateKeyRef = ref()
// 更新令牌
const handleUpdateKey = (id) => {
  updateKeyRef.value.open(id)
}
const handleStore = async (id) => {
  push(`/projectStore/storeManage?projectId=${id}`)
}
// 退出
const handleQuit = async (id) => {
  try {
    // 删除的二次确认
    await message.delConfirm('确定退出该项目？')
    // 发起删除
    await ProjectApi.getProjectMemberQuit({ projectId: id })
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

const toPublish = async (id) => {
  tagsViewStore.delAllViews()
  userStore.resetSetUser()
  appStore.setSelectProject(id)
  push(`/apiManage/publishSetting`)
}
/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
<style scoped lang="scss">
.el-dropdown {
  margin-top: 2px;
  margin-left: 10px;
}

.el-button.is-link {
  border: none !important;
  outline: none !important;
}
</style>
